﻿using AppSocketModel;
using BCGPSCommon;
using BCGPSMongoData;
using LJD.IMS.Utility;
using System;
using System.Collections.Generic;
using System.Text;

namespace AppSocketControl.GpsData.DataDispatch
{
    public class DispatchYECmdReturn
    {
        private readonly IRedisService redisService;
        private readonly MongoDBCommand<SimCardYEDto> mongoDBCommand;
        private SimCardYEDto  simCardYE = new SimCardYEDto();
        public DispatchYECmdReturn()
        {
            redisService = new RedisService();
            mongoDBCommand = new MongoDBCommand<SimCardYEDto>("CmdSimCardYEHistory");
        }

        private void Split(string[] dataArr)
        {
            simCardYE.IMEI = dataArr[5];

            simCardYE.CmdDateTime = MongoDBDateTime.GetNowUtc();
            simCardYE.CmdToward = "Receive";
            simCardYE.Result = dataArr[7];

            if(!string.IsNullOrWhiteSpace(simCardYE.Result) )
            {
                string[] arr = simCardYE.Result.Split('\n');
                for (int i = 0; i < arr.Length; i++)
                { 
                    if (arr[i].IndexOf("REC UNREAD") > 0)
                    {
                        if( ++i < arr.Length)
                        { 
                            if(!string.IsNullOrWhiteSpace(arr[i]))
                            {
                                string str = arr[i].TrimEnd('\r');
                                string msg2 = "";
                                int index = 0;
                                while (index < str.Length)
                                {
                                    try
                                    {
                                        msg2 += "\\u" + str.Substring(index, 4);
                                        index += 4;
                                    }
                                    catch
                                    {
                                        break;
                                    }
                                }
                                simCardYE.ResultChs = StringHelper.Unicode2String(msg2);
                            }
                        }
                    }
                }
            }

        }
        /// <summary>
        /// 设备运行状态数据写入数据库
        /// </summary>
        /// <param name="dataArr"></param>
        public void Run(string[] dataArr)
        {
            Split(dataArr);
            mongoDBCommand.InsertDocumentAsync(simCardYE).GetAwaiter().GetResult();
            redisService.AddAsync(GeneralContainer.RedisNameSpaceIMEISendCmd + simCardYE.IMEI, string.Empty).GetAwaiter().GetResult();
        }
    }
}
